package org.dromara.pe.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.pe.domain.Area;
import org.dromara.pe.domain.vo.AchievementExcelVo;
import org.springframework.stereotype.Service;
import org.dromara.pe.domain.bo.AchievementBo;
import org.dromara.pe.domain.vo.AchievementVo;
import org.dromara.pe.domain.Achievement;
import org.dromara.pe.mapper.AchievementMapper;
import org.dromara.pe.service.IAchievementService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 体测成绩管理Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-02
 */
@RequiredArgsConstructor
@Service
public class AchievementServiceImpl implements IAchievementService {

    private final AchievementMapper baseMapper;

    /**
     * 查询体测成绩管理
     */
    @Override
    public AchievementVo queryById(Long achievementId){
        return baseMapper.selectVoById(achievementId);
    }

    /**
     * 查询体测成绩管理列表
     */
    @Override
    public TableDataInfo<AchievementVo> queryPageList(AchievementBo bo, PageQuery pageQuery) {
        QueryWrapper<Achievement> lqw = buildQueryWrapper(bo);
        Page<AchievementVo> result = baseMapper.selectAchievementList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询体测成绩管理列表
     */
    @Override
    public List<AchievementVo> queryList(AchievementBo bo) {
        QueryWrapper<Achievement> lqw = buildQueryWrapper(bo);
        return baseMapper.selectAchievementList(lqw);
    }

    @Override
    public List<AchievementExcelVo> queryExportList(AchievementBo bo) {
        QueryWrapper<Achievement> lqw = buildQueryWrapper(bo);
        List<AchievementExcelVo> list = baseMapper.selectAchievementExcelListForTask(lqw);

        return list;
    }

    private QueryWrapper<Achievement> buildQueryWrapper(AchievementBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<Achievement> lqw =new QueryWrapper<>();
        lqw.eq(StringUtils.isNotBlank(bo.getStuNum()), "ppa.stu_num", bo.getStuNum());
        lqw.eq(StringUtils.isNotBlank(bo.getGender()), "pmi.gender", bo.getGender());
        lqw.eq(StringUtils.isNotBlank(bo.getGrade()), "ppa.grade", bo.getGrade());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), "ppa.status", bo.getStatus());
        lqw.like(StringUtils.isNotBlank(bo.getTaskName()), "peti.task_name ", bo.getTaskName());
        lqw.eq(bo.getTaskId()!=null, "ppa.task_id ", bo.getTaskId());
        lqw.eq(StringUtils.isNotBlank(bo.getSemester()), "ppa.semester", bo.getSemester());
        lqw.eq(StringUtils.isNotBlank(bo.getAcademicYear()), "ppa.academic_year", bo.getAcademicYear());
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), "pmi.name", bo.getStudentName());
        lqw.eq(bo.getClassId()!=null, "pbtc.class_id", bo.getClassId());
        lqw.eq(StringUtils.isNotBlank(bo.getYears()), "pmi.years", bo.getYears());
        lqw.eq(bo.getDeptId()!=null, "pbtc.dept_id", bo.getDeptId());
        lqw.eq(bo.getCollegeId()!=null, "sd2.dept_id", bo.getCollegeId());
        lqw.eq(bo.getProfessionalId()!=null, "sd1.dept_id", bo.getProfessionalId());

        return lqw;
    }

    /**
     * 新增体测成绩管理
     */
    @Override
    public Boolean insertByBo(AchievementBo bo) {
        Achievement add = MapstructUtils.convert(bo, Achievement.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setAchievementId(add.getAchievementId());
        }
        return flag;
    }

    /**
     * 修改体测成绩管理
     */
    @Override
    public Boolean updateByBo(AchievementBo bo) {
        Achievement update = MapstructUtils.convert(bo, Achievement.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Achievement entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除体测成绩管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 批量插入体测成绩
     *
     * @param taskId 任务 ID
     * @param stuNums 学生编号列表
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertAchievementsByTask(Long taskId, List<String> stuNums,String academicYear,String semester) {
        // 使用 stream API 遍历学生编号列表，生成 Achievement 对象列表
        List<Achievement> achievements = stuNums.stream().map(stuNum -> {
            Achievement achievement = new Achievement();
            // 设置任务 ID 和学生编号
            achievement.setTaskId(taskId);
            achievement.setStuNum(stuNum);
            achievement.setAcademicYear(academicYear);
            achievement.setSemester(semester);
            // 其他字段初始化
            return achievement;
        }).collect(Collectors.toList());

        return baseMapper.insertBatch(achievements);
    }
    public Boolean deleteAchievementByBatch(Long taskId) {
        // 使用 stream API 遍历学生编号列表，生成 Achievement 对象列表

        LambdaQueryWrapper<Achievement> lqw = Wrappers.lambdaQuery();
        lqw.eq(taskId!=null, Achievement::getTaskId, taskId);
        return baseMapper.delete(lqw)>0;
    }



}
